package com.wendu.oa.gateway;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wendu.oa.common.Constants;
import com.wendu.oa.common.Result;
import com.wendu.oa.common.TokenUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
public class TokenFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange,
                             GatewayFilterChain chain)
    {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取应用内的请求路径
        String path = request.getPath().pathWithinApplication().value();

        if("/security/login".equals(path)){
            //放行不需要验证token的接口
            return chain.filter(exchange);
        }

        //获取客户端携带的token
        String clientToken = request.getHeaders().getFirst(Constants.HEADER_TOKEN);

        try {
            //对客户端携带的token进行验证
            TokenUtils.verify(clientToken);
        } catch (Exception e) {//token验证未通过
            e.printStackTrace();
            return voidMono(response,
                    Result.err(Result.CODE_ERR_UNLONINED,
                            e.getMessage())
            );
        }

        try{
            //放行请求
            return chain.filter(exchange);
        }catch (Exception e) {//请求错误
            e.printStackTrace();
            return voidMono(response,
                    Result.err(Result.CODE_ERR_SYS,e.getMessage())
            );
        }
    }

    //向客户端发送响应结果
    private Mono<Void> voidMono(ServerHttpResponse serverHttpResponse,
                                Result result)  {
        try {
            serverHttpResponse.getHeaders().add("Content-Type",
                    "application/json;charset=UTF-8");
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonString = objectMapper.writeValueAsString(result);
            DataBuffer dataBuffer =
                    serverHttpResponse
                            .bufferFactory()
                            .wrap(jsonString.getBytes("UTF-8"));
            return serverHttpResponse.writeWith(Flux.just(dataBuffer));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    //设置过滤器的优先级为最优先
    @Override
    public int getOrder() {
        return -100;
    }
}
